import React, { useState } from "react";
import { Form } from "antd";
import img1 from "@/assets/1.png";
import img2 from "@/assets/2.png";
import styles from "./index.module.scss";
import classNames from "classnames/bind";
import { Login, Rigister } from "../../../domain/login/service";
import { useNavigate } from "react-router-dom";
import { Spin, message } from "antd";
import localstorage from '../../../base/utils/storage'
import MyInput from "@/components/myInput";
const cx = classNames.bind(styles);
const LoginPage: React.FC = () => {
  const navigate = useNavigate();
  const [isLogin, setIsLogin] = useState(true);
  const [registerFormData, setRegisterFormData] = useState<formDataType>({
    username: "",
    password: "",
  });
  const [loginFormData, setLoginFormData] = useState<loginFormDataType>({
    username: "",
    password: "",
  });
  const [isLoading, setIsLoading] = useState(false);
  const toRegister = () => {
    setIsLogin(false);
  };

  //注册的参数类型
  interface formDataType {
    username: string;
    password: string;
  }

  //登录的参数类型
  interface loginFormDataType {
    username: string;
    password: string;
  }
  const toLogin = () => {
    setIsLogin(true);
    setRegisterFormData({
      username: "",
      password: "",
    });
  };

  const nameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRegisterFormData((item) => ({
      ...item,
      username: event.target.value,
    }));
    console.log(event.target.value);
  };

  const passwordChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setRegisterFormData((item) => ({ ...item, password: event.target.value }));
  };

  const countNameChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setLoginFormData((item) => ({
      ...item,
      username: event.target.value,
    }));
  };

  const loginPasswordChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setLoginFormData((item) => ({
      ...item,
      password: event.target.value,
    }));
  };

  const rigister = async () => {
    if (validate(1)) {
      setIsLoading(true);
      await Rigister(registerFormData)
        .then((res) => {
          console.log(res.data, "res");
          message.success("注册成功");
          toLogin();
          
        })
        .catch((err) => {
          console.log(err.response.data);
          message.error(err.response.data.data);
        });
      setIsLoading(false);
    } else {
      message.error("请检查表单项");
    }
  };

  const LoginFuc = async () => {
    if (validate(0)) {
      await Login(loginFormData)
        .then((res) => {
          if (res.data.code === 201) {
            const accessToken = res.data.data.accessToken
            const refreshToken = res.data.data.refreshToken
            localstorage.set('accesstoken',accessToken)
            localstorage.set('refreshToken',refreshToken)
            navigate("/pages");
            message.success("登录成功");
          }
        })
        .catch((err) => {
          console.log(err,'err');
        });
    } else {
      message.error("请检查表单项");
    }
  };
  const validate = (tag: number) => {
    if (tag === 0) {
      //登录的验证
      if (loginFormData.username && loginFormData.password) {
        return true;
      } else return false;
    } else {
      if (
        registerFormData.username &&
        registerFormData.password &&
        registerFormData.password.length >= 6
      ) {
        return true;
      } else return false;
    }
  };

  const handleKeyDown = (event: { key: string; preventDefault: () => void; }) => {
    if (event.key === 'Enter') {
      event.preventDefault(); // 阻止默认行为
      LoginFuc()
    }
  };
  return (
    <Spin spinning={isLoading}>
      <div className={cx("background")}>
        <div className={cx("container")}>
          <div
            className={cx("form-box")}
            style={{
              transform: isLogin ? "translateX(0%)" : "translateX(80%)",
            }}
          >
            <Form>
              {/* 注册页 */}
              <div className={cx("register-box", { hidden: isLogin })}>
                <h1> register</h1>
                <MyInput
                  type="text"
                  placeholder="用户名"
                  handleChange={nameChange}
                  required
                  value={registerFormData.username}
                />
                <MyInput
                  type="password"
                  placeholder="密码"
                  handleChange={passwordChange}
                  required
                  minLength={6}
                  value={registerFormData.password}
                />
                <div>
                  <button onClick={rigister}>注册</button>
                </div>
              </div>

              {/* 登陆页 */}
              <div className={cx("login-box", { hidden: !isLogin })}>
                <h1>登录</h1>
                {/* <input placeholder="用户名" onChange={countNameChange} /> */}
                <MyInput
                  placeholder="用户名"
                  handleChange={countNameChange}
                  required
                  MyOnkeydown={handleKeyDown}
                />
                <MyInput
                  placeholder="密码"
                  handleChange={loginPasswordChange}
                  required
                  type="password"
                  MyOnkeydown={handleKeyDown}
                />
                <div
                  style={{
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  <button onClick={LoginFuc}>登录</button>
                </div>
              </div>
            </Form>
          </div>
          <div className={cx(["con-box", "left"])}>
            <h2>
              欢迎来到<span>旅梦后台</span>
            </h2>
            <p>
              准备好成为旅梦<span>大佬</span>吗？
            </p>
            <img src={img1} alt=""></img>
            <p>已有账号</p>
            <button id="login" onClick={toLogin}>
              去登录
            </button>
          </div>

          <div className={cx(["con-box", "right"])}>
            <h2>
              欢迎来到<span>旅梦后台</span>
            </h2>
            <p>
              登录成为<span>大佬</span>吧
            </p>
            <img src={img2} alt=""></img>
            <p>没有账号？</p>
            <button id="register" onClick={toRegister}>
              去注册
            </button>
          </div>
        </div>
      </div>
    </Spin>
  );
};

export default LoginPage;
